<?php

/**
 * EmsSection form.
 *
 * @package    ems1
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class EmsSectionForm extends BaseEmsSectionForm
{
    private static $nums = array(
        3 => 3,
        4 => 4,
        5 => 5,
        6 => 6,
        7 => 7,
        8 => 8,
        9 => 9,
        10 => 10,
        11 => 11,
        12 => 12,
        13 => 13,
        14 => 14,
        15 => 15,
        16 => 16,
        17 => 17,
        18 => 18,
        19 => 19,
        20 => 20,
    );

    public function configure()
    {
        unset(
            $this['created_at'], $this['updated_at'], $this['has_subsection']
        );

        $this->widgetSchema['slug'] = new sfWidgetFormInputHidden();

        $this->widgetSchema['portal_id'] = new sfWidgetFormInputHidden();

        $this->widgetSchema['type_id'] = new sfWidgetFormInputHidden();

        $this->widgetSchema['is_subsection'] = new sfWidgetFormInputHidden();

        $this->widgetSchema['structure'] = new sfWidgetFormInputHidden();

        $this->validatorSchema['structure'] = new sfValidatorString(array('required' => false,'max_length' => 255));

        $user = sfContext::getInstance()->getUser();

        if ($this->getObject()->exists()) {
            if(!$user->hasCredential('Habilitar sección')){
                unset($this['is_enabled']);
            } else {
                $this->widgetSchema['is_enabled']->setLabel('Habilitar');
            }
        } else {
            unset ($this['is_enabled']);
        }

        if(!$user->hasCredential('Publicar sección')){
            unset($this['published']);
        } else {
            $this->widgetSchema['published']->setLabel('Publicar');
        }

        if($this->getObject()->getType()->getType() == 'News' ||
            $this->getObject()->getType()->getType() == 'Gallery' ||
            $this->getObject()->getType()->getType() == 'Download'
        ){
            $this->widgetSchema['max_contents_per_page'] = new sfWidgetFormChoice(array(
                'choices'  => self::$nums,
                'multiple' => false,
                'expanded' => false,
                'label'    => 'Paginar contenidos cada',
            ));

            $this->validatorSchema['max_contents_per_page'] = new sfValidatorChoice(array(
                'choices' => array_keys(self::$nums),
            ));
        } else {
            $this->getObject()->setMaxContentsPerPage(0);
            $this->widgetSchema['max_contents_per_page'] = new sfWidgetFormInputHidden();
        }

        $this->validatorSchema['title']->setMessage('required', 'Campo obligatorio.');

        $this->widgetSchema->setLabels(array(
                'title'       => 'Titulo',
                'uses_header' => 'Con header',
                'uses_footer' => 'Con footer',
                'summary'     => 'Reseña',
                'can_comment' => 'Con comentarios'
            ));

        switch ($this->getObject()->getType()->getType()) {
          case 'News':
              if($this->getObject()->getNewsSection()->isNew()){
                  $news = new EmsNewsSection();
                  $news->setContentType(Doctrine::getTable('EmsContentType')->findOneByType('Article'));
                  $this->getObject()->setNewsSection($news);
              }

              $form = new EmsNewsSectionForm($this->getObject()->getNewsSection());
              $this->embedForm('News', $form);
              break;
          case 'Gallery':
              if($this->getObject()->getGallerySection()->isNew()){
                  $gallery = new EmsGallerySection();
                  $this->getObject()->setGallerySection($gallery);
              }
              $form = new EmsGallerySectionForm($this->getObject()->getGallerySection());
              $this->embedForm('Gallery', $form);
              break;
          case 'Download':
              if($this->getObject()->getDownloadSection()->isNew()){
                  $download = new EmsDownloadSection();
                  $this->getObject()->setDownloadSection($download);
              }
              $form = new EmsDownloadSectionForm($this->getObject()->getDownloadSection());
              $this->embedForm('Download', $form);
              break;
          case 'Register':
              if($this->getObject()->getRegisterSection()->isNew()){
                  $register = new EmsRegisterSection();
                  $this->getObject()->setRegisterSection($register);
              }
              $form = new EmsRegisterSectionForm($this->getObject()->getRegisterSection());
              $this->embedForm('Register', $form);
              break;
          case 'Flat':
              if($this->getObject()->getFlatSection()->isNew()){
                  $flat = new EmsFlatSection();
                  $this->getObject()->setFlatSection($flat);
              }
              $form = new EmsFlatSectionForm($this->getObject()->getFlatSection());
              $this->embedForm('Flat', $form);
              break;
          case 'Home':
              if($this->getObject()->getHomeSection()->isNew()){
                  $home = new EmsHomeSection();
                  $this->getObject()->setHomeSection($home);
              }
              $form = new EmsHomeSectionForm($this->getObject()->getHomeSection());
              $this->embedForm('Home', $form);
              unset($this['is_enabled']);
              break;
          default:
              break;
        }

        $this->validatorSchema->setPostValidator(
            new sfValidatorDoctrineUnique(
                    array('model' => 'EmsSection', 'column' => array('portal_id','title')),
                    array('invalid' => 'Existe otra sección con el mismo Titulo.')
                )
            );
    }

    public function bind(array $taintedValues = null, array $taintedFiles = null)
    {
        $taintedValues['slug'] = Slug::slugger($taintedValues['title']);
        $taintedValues['structure'] = $this->getObject()->getStructure();

        if(!$this->getObject()->exists()){
            $taintedValues['structure'] = str_repeat('c', $taintedValues['max_contents_per_page']);
        }

        parent::bind($taintedValues, $taintedFiles);
    }

    /*
     *  This is for rearrange the order for rendering contents and elements when
     *  the 'max_contents_per_page' parameter is modified.
     */
    protected function doUpdateObject($values)
    {
        if($this->getObject()->exists()){
            if($this->getObject()->getMaxContentsPerPage() != $values['max_contents_per_page']) {
                $old = $this->getObject()->getMaxContentsPerPage();
                $new = $values['max_contents_per_page'];
                $structure = $this->getObject()->getStructure();
                
                if($old < $new){
                    $dif = $new - $old;
                    $values['structure'] = str_repeat('c', $dif);
                } else {
                    $dif = $old - $new;
                    $old_structure = $structure;
                    $limit = 0;

                    for ($i = 0; $i < $dif; $i++) {
                        $limit = strripos($structure, 'c');
                        $structure = substr_replace($structure, '', $limit, 1);
                    }

                    $values['structure'] = $structure;

                    if(strlen($structure) > $limit) {
                        $old_elems_pos = array();
                        $pos = 0;

                        while ($pos !== false && $pos != strlen($old_structure) ) {
                            $pos = stripos($old_structure, 'e', $pos);
                            if($pos !== false){
                                $pos = $pos + 1;
                                array_push($old_elems_pos, $pos);
                            }
                        }

                        $new_elems_pos = array();
                        $pos = 0;

                        while ($pos !== false && $pos != strlen($structure) ) {
                            $pos = stripos($structure, 'e', $pos);

                            if($pos !== false){
                                $pos = $pos + 1;
                                array_push($new_elems_pos, $pos);
                            }
                        }

                        $elements = $this->getObject()->getElementsForRender();

                        foreach ($old_elems_pos as $key => $old_pos){
                            if($old_pos > $limit){
                                $element = $elements[$old_pos];
                                $element = new EmsElement();
                                $element->setPosition($new_elems_pos[$key])->save();
                            }
                        }
                    }
                }
            }
        }
        
        parent::doUpdateObject($values);
    }
}
